# -*- coding: utf-8 -*-
"""
独立截图工具：复用 window_spy.WindowSpyGUI，只启动截图覆盖层。

运行方式:
  方式1(模块): python -m modules.screenshot.screenshot_tool
  方式2(根目录): python screenshot_tool.py
  
打包后可直接双击启动截图。
"""

# 在任何tkinter导入之前设置环境
import sys
import os
from modules.tkinter_setup import setup_tcltk_environment
setup_tcltk_environment()

# 添加项目根目录到路径(支持模块化运行)
if __name__ == '__main__':
    # 获取项目根目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    root_dir = os.path.dirname(os.path.dirname(current_dir))
    if root_dir not in sys.path:
        sys.path.insert(0, root_dir)

import tkinter as tk

try:
    from window_spy import WindowSpyGUI
except Exception as e:
    print("导入 window_spy 失败:", e)
    print("请确保从项目根目录运行此脚本")
    sys.exit(1)


def main():
    root = tk.Tk()
    # 先隐藏主窗口，只显示截图覆盖层
    try:
        root.withdraw()
    except Exception:
        pass

    app = WindowSpyGUI(root)

    # 防御：若截图确认依赖的 label 不存在，则提供一个隐藏 label
    try:
        if not hasattr(app, 'screenshot_thumb_label') or app.screenshot_thumb_label is None:
            hidden = tk.Label(root)
            hidden.place_forget()
            app.screenshot_thumb_label = hidden
    except Exception:
        pass

    # 启动后立刻进入截图模式
    root.after(100, app.open_selection_overlay)

    # 截图完成或取消后自动退出整个程序
    def _quit_on_close():
        try:
            root.after(100, root.quit)
        except Exception:
            try:
                root.destroy()
            except Exception:
                pass

    # 将内部的关闭操作挂钩到退出
    orig_cancel = getattr(app, '_cancel_selection', None)
    def wrap_cancel(*args, **kwargs):
        try:
            if orig_cancel:
                orig_cancel(*args, **kwargs)
        finally:
            _quit_on_close()
    if orig_cancel:
        app._cancel_selection = wrap_cancel  # 替换

    orig_confirm = getattr(app, '_confirm_selection', None)
    def wrap_confirm(*args, **kwargs):
        try:
            if orig_confirm:
                orig_confirm(*args, **kwargs)
        finally:
            _quit_on_close()
    if orig_confirm:
        app._confirm_selection = wrap_confirm  # 替换

    try:
        root.mainloop()
    finally:
        try:
            root.destroy()
        except Exception:
            pass


if __name__ == '__main__':
    main()


